package org.siteanalyser.util;

import org.apache.commons.lang.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Miscellaneous HTML parsing methods.
 * 
 * @author Luc Russell
 * 
 */
public class HtmlParseUtil {

    private static final String HTTP_PROTOCOL = "http://";
    private static final String GOOGLE_ANALYTICS_ID = ".google-analytics.com/ga.js";

    public static String getBodyText(final Document doc) {
        final Element content = doc.getElementsByTag("body").first();
        if (content != null) {
            return content.text();
        } else {
            return "";
        }
    }

    public static double getTextPercentage(final Document doc) {
        double result = 0d;
        final String text = getBodyText(doc);
        final String allHtml = doc.outerHtml();

        if (allHtml.length() > 0 && text.length() > 0) {
            final int htmlLength = allHtml.length() - text.length();
            result = PercentageCalculator.aIsWhatPercentOfB(text.length(), htmlLength);
        }
        return result;
    }

    public static boolean getGoogleAnalytics(final Document doc) {
        final Elements elements = doc.getElementsByAttributeValue("type", "text/javascript");
        boolean isGAPresent = false;
        for (final Element script : elements) {
            if (StringUtils.containsIgnoreCase(script.data(), GOOGLE_ANALYTICS_ID)) {
                isGAPresent = true;
                break;
            }
        }
        return isGAPresent;
    }

    public static String addProtocol(final String url) {
        final StringBuffer tidiedUrl = new StringBuffer();
        if (!url.startsWith(HTTP_PROTOCOL)) {
            tidiedUrl.append(HTTP_PROTOCOL);
        }
        tidiedUrl.append(url);
        return tidiedUrl.toString();
    }

    public static String removeProtocol(final String url) {
        return StringUtils.remove(url, HTTP_PROTOCOL);
    }
}
